package com.uenpay.im.ui.old.activity.dynamic;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AbsListView.RecyclerListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aswife.ui.MaskImageView;
import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qiyunxin.android.http.cache.HttpStreamCache;
import com.qiyunxin.android.http.common.ImageUtil;
import com.qiyunxin.android.http.listener.OnUploadFileListener;
import com.qiyunxin.android.http.net.HttpRequestAsyncTaskQueue;
import com.qiyunxin.android.http.net.HttpUploadFileAsyncTask;
import com.qiyunxin.android.http.utils.FileUtils;
import com.qiyunxin.android.http.utils.Utils;
import com.qiyunxin.android.http.view.ResizeLayout;
import com.qyx.android.message.type.PacketType;
import com.qyx.android.weight.choosemorepic.PhotoItem;
import com.uenpay.im.BroadcastAction;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.CameraActivity;
import com.uenpay.im.ui.old.activity.chat.ActivityHandle;
import com.uenpay.im.ui.old.activity.choosemorepic.PhotoActivity;
import com.uenpay.im.callback.IOnBottomDialogListener;
import com.uenpay.im.callback.OnBottomDialogListener;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.entities.ImageSize;
import com.uenpay.im.panel.FacePanelByEmojiManager;
import com.uenpay.im.panel.PanelManagerInterface;
import com.uenpay.im.weight.BottomDialog;
import com.uenpay.im.weight.RoundImageView;
import com.uenpay.im.weight.listview.RefreshListView;
import com.uenpay.util.app.base.BaseActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.text.MessageFormat;
import java.util.ArrayList;

/**
 * friends dynamic list
 *
 * @author Sl
 * @copyRight http://www.qiyunxin.com
 */
public class DynamicActivity extends BaseActivity implements OnClickListener,
        RefreshListView.IRefreshListViewListener {
    private updatemsgcountBroadcastReceiver mBroadcastReceiver = null;
    private DynamicHandle mDynamicHandle = new DynamicHandle();
    /**
     * ====not read dynamic msg layout===
     */
    private LinearLayout not_read_messages_layout;
    private View bottom_view;
    private TextView notReadMessageNoticeTv;
    private RoundImageView last_dynamic_avatar;
    /**
     * =======
     */
    private RefreshListView mListView;
    private TextView nick_tv;
    private RoundImageView photo_iv;
    private MaskImageView bg_dynamic_iv;
    private ArrayList<DynamicEntity> dynamics = new ArrayList<DynamicEntity>();
    private static final int SEND_DYNAMIC = 2;
    private View loading;
    private int page = 1;
    private int replyDynamicId;
    private EditText editText;
    private View dynamic_pop_reply;
    protected FileUtils fileUtils = new FileUtils(IMApplication.appName);
    private static final int PAIS = 1;
    private static final int PIC = 0;
    private DynamicAdapter adapter;
    private LinearLayout linearLayout1;
    private boolean is_restore;
    private int replySourceCustId;
    private String picPath;
    private ArrayList<PhotoItem> select_gl_arr = new ArrayList<PhotoItem>();
    private ArrayList<ImageSize> size = new ArrayList<ImageSize>();
    private Handler handler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {

            switch (msg.what) {
                case 3:
                    alterAlbumBg();
                    break;
                case 5:
                    if (page == 1) {
                        if (adapter != null) {
                            adapter.setData(dynamics);
                        } else {
                            initData();
                        }
                        mListView.setSelection(0);
                        page++;
                        mListView.setPullLoadEnable(true);
                    } else {
                        ArrayList<DynamicEntity> arraylist = (ArrayList<DynamicEntity>) msg.obj;
                        if (arraylist != null && arraylist.size() > 0) {
                            adapter.addData(arraylist);
                            page++;
                        } else {
                            mListView.setPullLoadEnable(false);
                        }
                    }
                    break;
                case 6:
                    if (loading != null) {
                        loading.setVisibility(View.GONE);
                    }
                    break;
                default:
                    break;
            }

            return false;
        }
    });

    private FacePanelByEmojiManager mFacePanelByEmojiManager;
    private ResizeLayout mResizeLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        super.onCreate(savedInstanceState);
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_friend_dynamic;
    }

    @Override
    public void initView(View view) {
        loading = findViewById(R.id.dynamic_loading);
        loading.setVisibility(View.VISIBLE);
        initView();
        initListener();
        initFacePanelView();
        initData();
        getDynamic();
    }

    private void initFacePanelView() {
        mFacePanelByEmojiManager = new FacePanelByEmojiManager(this,
                dynamic_pop_reply, mResizeLayout);
        mFacePanelByEmojiManager.initListener();
        mFacePanelByEmojiManager.onSendTextListener(new PanelManagerInterface.ISendTextListener() {

            @Override
            public void onSendTextContent(String editContent) {
                if (!TextUtils.isEmpty(editContent.trim())) {
                    if (editContent.length() <= 140) {
                        Utils.hideSoftKeyboard(editText);
                        dynamic_pop_reply.setVisibility(View.GONE);
                        if (is_restore) {
                            replyDynamic(editContent);
                            is_restore = false;
                            editText.setHint("");
                        } else {
                            replyDynamic(editContent);
                        }

                    } else {
                        IMApplication.showToast(R.string.more_text_max);
                    }
                } else {
                    IMApplication.showToast(R.string.reply_empty);
                }
            }
        });
    }

    protected void initView() {
        findViewById(R.id.title_right_layout).setOnClickListener(this);
        findViewById(R.id.title_right_layout).setVisibility(View.VISIBLE);
        ((TextView) findViewById(R.id.title_textview))
                .setText(R.string.friend_circle);
        ((TextView) findViewById(R.id.title_right_tv)).setText(R.string.send);
        mListView = (RefreshListView) findViewById(R.id.listview_dynamic);
        mListView.setScrollingCacheEnabled(false);
        mListView.setFastScrollEnabled(false);
        editText = (EditText) findViewById(R.id.editText);
        dynamic_pop_reply = findViewById(R.id.dynamic_pop_reply);
        mResizeLayout = (ResizeLayout) findViewById(R.id.parent);
        View view = LayoutInflater.from(this).inflate(
                R.layout.activity_friend_dynamic_head, null);
        mListView.addHeaderView(view);
        not_read_messages_layout = (LinearLayout) view
                .findViewById(R.id.not_read_messages_layout);
        bottom_view = view.findViewById(R.id.bottom_view);
        notReadMessageNoticeTv = (TextView) findViewById(R.id.not_read_message_tv);
        last_dynamic_avatar = (RoundImageView) findViewById(R.id.last_dynamic_avatar);
        nick_tv = (TextView) view.findViewById(R.id.nick_tv);
        photo_iv = (RoundImageView) view.findViewById(R.id.dynamic_photo_btn);
        bg_dynamic_iv = (MaskImageView) view.findViewById(R.id.bg_dynamic_iv);
        linearLayout1 = (LinearLayout) view.findViewById(R.id.linearLayout1);
        nick_tv.setText(IMApplication.config.getUserName());
        photo_iv.SetUrl(APIConfiguration.getAvatarUrlNormal(
                IMApplication.getCustId(), PacketType.PERSONAL));

        if (!TextUtils.isEmpty(IMApplication.config.getDynamicBg())) {
            linearLayout1.setVisibility(View.GONE);
            bg_dynamic_iv.SetUrl(IMApplication.config.getDynamicBg());
        }
    }

    protected void initListener() {
        mListView.setPullLoadEnable(true);
        mListView.setRefreshListViewListener(this);
        findViewById(R.id.back_layout).setOnClickListener(this);
        photo_iv.setOnClickListener(this);
        bg_dynamic_iv.setOnClickListener(this);

        mListView.setRecyclerListener(new RecyclerListener() {
            @Override
            public void onMovedToScrapHeap(View view) {
                if (view.getTag() instanceof DynamicAdapterViewHolder.DynamicBaseViewHolder) {
                    DynamicAdapterViewHolder.DynamicBaseViewHolder holder = (DynamicAdapterViewHolder.DynamicBaseViewHolder) view
                            .getTag();
                    if (holder == null) {
                        return;
                    }
                    if (holder.position >= mListView.getFirstVisiblePosition()
                            && holder.position <= mListView
                            .getLastVisiblePosition()) {
                        return;
                    }
                    holder.mReplyLLayout.removeAllViews();
                }
            }
        });

        mListView.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (mFacePanelByEmojiManager != null) {
                    mFacePanelByEmojiManager.hideFacePanelView();
                }
                dynamic_pop_reply.setVisibility(View.GONE);
                return false;
            }
        });
        not_read_messages_layout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                ActivityHandle.startActivity(DynamicActivity.this,
                        DynamicHistoryActivity.class, null, -1);
            }
        });
    }

    /**
     * 动态数据
     */
    private void initData() {
        adapter = new DynamicAdapter(editText, this, dynamics,
                new DynamicAdapter.IDynamicReplyListener() {

                    @Override
                    public void onDynamicReply(int dynamicId,
                                               int source_cust_id, int position) {
                        replyDynamicId = dynamicId;
                        replySourceCustId = source_cust_id;
                        if (source_cust_id > 0) {
                            is_restore = true;
                        }
                        /**
                         * 评论动态
                         */
                        dynamic_pop_reply.setVisibility(View.VISIBLE);
                        if (mFacePanelByEmojiManager != null) {
                            mFacePanelByEmojiManager.showFacePanelView();
                            Utils.showSoftKeyboard(editText);
                        }
                        mListView.setSelection(mListView.getHeaderViewsCount()
                                + position);

                    }
                });
        mListView.setAdapter(adapter);
    }

    @Override
    protected void onResume() {
        showNotReadDynamicLayout();
        if (mBroadcastReceiver == null) {
            mBroadcastReceiver = new updatemsgcountBroadcastReceiver();
            IntentFilter mFilter = new IntentFilter(
                    BroadcastAction.DISCOVER_UNREAD_COUNT_ACTION);
            registerReceiver(mBroadcastReceiver, mFilter);
        }
        super.onResume();
    }

    /**
     * 评论动态
     *
     * @param content
     */
    private void replyDynamic(final String content) {
        loading.setVisibility(View.VISIBLE);
        mDynamicHandle.replyDynamic(replySourceCustId, replyDynamicId, content,
                new DynamicHandle.IReplyDynamicResultListener() {

                    @Override
                    public void onReplyDynamicReslut(int status, String msg,
                                                     Reply mReply) {
                        if (isFinishing())
                            return;
                        handler.sendEmptyMessage(6);
                        if (status == HttpInvokeResultCode.RESULT_OK) {
                            editText.setText("");
                            Utils.hideSoftKeyboard(editText);
                            Reply r = new Reply();
                            r.replyid = mReply.replyid;
                            r.nickname = IMApplication.config.getUserName();
                            r.content = mReply.content;
                            r.custid = mReply.custid;
                            r.pcustid = mReply.pcustid;
                            r.pnickname = mReply.pnickname;
                            adapter.updateReply(r, replyDynamicId);
                        }
                    }
                });

    }

    public void alterAlbumBg() {
        String url = APIConfiguration.getBaseUrl()
                + "Dynamic/Dynamic/setBackground?"
                + APIConfiguration.getCustIdAndToken();
        if (picPath.startsWith("http")) {
            picPath = HttpStreamCache.getInstance().GetFilePath(picPath);
        }
        HttpRequestAsyncTaskQueue.getInstance().AddTask(
                new HttpUploadFileAsyncTask("1", picPath, url, "uploadedFile") {

                }, new OnUploadFileListener() {

                    @Override
                    public void OnSuccess(String key, String response) {
                        FileMessage fileMessage = new FileMessage();
                        try {
                            JSONObject json = new JSONObject(response);
                            fileMessage.status = json.optInt("status");
                            JSONObject dataJson = json.optJSONObject("data");
                            if (dataJson != null) {
                                JSONObject dynamicSetting = dataJson
                                        .optJSONObject("dynamicsetting");
                                if (dynamicSetting != null) {
                                    fileMessage.filehash = dynamicSetting
                                            .optString("bgfilehash");
                                    fileMessage.fileid = dynamicSetting
                                            .optString("bgfileid");
                                }

                                IMApplication.config
                                        .setDynamicBg(APIConfiguration
                                                .getFileDownloadPath(
                                                        fileMessage.fileid,
                                                        fileMessage.filehash));
                                bg_dynamic_iv.SetUrl(APIConfiguration
                                        .getFileDownloadPath(
                                                fileMessage.fileid,
                                                fileMessage.filehash));
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void OnFail(String key, String reason) {

                    }
                });

        linearLayout1.setVisibility(View.GONE);
    }

    public void getDynamic() {
        mDynamicHandle.getDynamicList(page,
                new DynamicHandle.IGetDynamicListResultListener() {

                    @Override
                    public void onGetDynamicResult(int status, String msg,
                                                   ArrayList<DynamicEntity> ResultDynamics) {

                        onLoad();
                        handler.sendEmptyMessage(6);
                        if (isFinishing()) {
                            return;
                        }
                        if (status == HttpInvokeResultCode.RESULT_OK) {
                            if (ResultDynamics != null) {
                                if (ResultDynamics.size() > 0) {
                                    dynamics = ResultDynamics;
                                    Message message = handler.obtainMessage();
                                    message.what = 5;
                                    message.obj = ResultDynamics;
                                    handler.sendMessage(message);
                                } else if (page != 1) {
                                    mListView.setPullLoadEnable(false);
                                }
                            } else if (page != 1) {
                                mListView.setPullLoadEnable(false);
                            }
                        }
                    }
                });
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.back_layout) {
            Utils.hideSoftKeyboard(editText);
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    finish();
                }
            }, 300);


        } else if (i == R.id.title_right_layout) {
            showDialog();

        } else if (i == R.id.bg_dynamic_iv) {
            showBgDialog();

        } else {
        }
    }

    private void showDialog() {
        BottomDialog.showBottomDynamicDialog(DynamicActivity.this, new OnBottomDialogListener() {
            @Override
            public void onClicked() {
                // TODO: 2017/3/1 小视频
                ActivityHandle.startActivity(DynamicActivity.this, SendDynamicVideoActivity.class, null, SEND_DYNAMIC);
            }
        }, new OnBottomDialogListener() {
            @Override
            public void onClicked() {
                // TODO: 2017/3/1 普通
                ActivityHandle.startActivity(DynamicActivity.this,
                        SendDynamicActivity.class, null, SEND_DYNAMIC);
            }
        });
    }


    public void showBgDialog() {

        BottomDialog.showBottomDialog(DynamicActivity.this, getResources()
                        .getString(R.string.take_photo),
                getResources().getString(R.string.take_image), getResources()
                        .getString(R.string.cancel), -1,
                new IOnBottomDialogListener() {

                    @Override
                    public void onClicked() {
                        size.clear();
                        size.add(new ImageSize(720, 720, ""));
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("size", size);
                        ActivityHandle.startActivity(DynamicActivity.this,
                                CameraActivity.class, bundle, PAIS);
                    }
                }, new IOnBottomDialogListener() {

                    @Override
                    public void onClicked() {
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("max_select_count", 1);
                        ActivityHandle.startActivity(DynamicActivity.this,
                                PhotoActivity.class, null, PIC);

                    }
                });

    }

    @SuppressWarnings("unchecked")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            File compressFile = null;
            Bitmap compressBitmap = null;
            switch (requestCode) {
                case SEND_DYNAMIC:
                    page = 1;
                    getDynamic();
                    break;
                case PAIS:
                    try {
                        picPath = data.getStringExtra("big_pic_filename");
                        handler.sendEmptyMessage(3);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case PIC:
                    try {
                        select_gl_arr.clear();
                        select_gl_arr = (ArrayList<PhotoItem>) data
                                .getSerializableExtra("gl_arr");

                        if (select_gl_arr.size() > 0) {
                            for (int i = 0; i < select_gl_arr.size(); i++) {
                                String path = select_gl_arr.get(i).getPath();
                                compressFile = new File(fileUtils.getAlbumDir(),
                                        Utils.md5(path) + ".jpg");
                                compressBitmap = ImageUtil.CompressImage(path, 90,
                                        720, 720);
                                FileOutputStream fos;
                                fos = new FileOutputStream(compressFile);
                                compressBitmap.compress(Bitmap.CompressFormat.JPEG,
                                        80, fos);
                                picPath = compressFile.getAbsolutePath();
                                handler.sendEmptyMessage(3);
                            }
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                default:
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onBackPressed() {
        if (dynamic_pop_reply != null
                && dynamic_pop_reply.getVisibility() == View.VISIBLE) {
            if (mFacePanelByEmojiManager != null) {
                mFacePanelByEmojiManager.hideFacePanelView();
            }
        } else {
            finish();
        }
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        if (adapter != null) {
            adapter.RecycleMaskImageView(true);
        }
        if (mBroadcastReceiver != null) {
            unregisterReceiver(mBroadcastReceiver);
        }
        super.onDestroy();
    }

    private void onLoad() {
        mListView.stopRefresh();
        mListView.stopLoadMore();
    }

    @Override
    public void onRefresh() {
        page = 1;
        getDynamic();
    }

    @Override
    public void onLoadMore() {
        getDynamic();
    }

    /***
     * 接受动态未读消息通知广播
     *
     * @author SL
     */
    public class updatemsgcountBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context arg0, Intent arg1) {
            if (arg1.getAction().equals(
                    BroadcastAction.DISCOVER_UNREAD_COUNT_ACTION)) {
                showNotReadDynamicLayout();
            }
        }

    }

    /***
     * 显示动态未读消息
     */
    private void showNotReadDynamicLayout() {
        int count = IMApplication.config.getDynamicUnreadMsgCount();
        if (count > 0) {
            not_read_messages_layout.setVisibility(View.VISIBLE);
            bottom_view.setVisibility(View.VISIBLE);
            notReadMessageNoticeTv.setText(MessageFormat.format(getResources()
                    .getString(R.string.unread_msg_tip), IMApplication.config
                    .getDynamicUnreadMsgCount()));
            last_dynamic_avatar.SetUrl(APIConfiguration.getAvatarUrlNormal(
                    IMApplication.config.getDynamicUnreadMsgCustId(),
                    PacketType.PERSONAL));
        } else {
            not_read_messages_layout.setVisibility(View.GONE);
            bottom_view.setVisibility(View.GONE);
        }
    }

}
